https://www.tuputech.com/
https://nodeschool.io/
Node.js npm express
Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.
Node.js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code server-side
##Event-driven:
也叫select/epoll,select/epoll的好处就在于单个process就可以同时处理多个网络连接的IO。它的基本原理就是select/epoll这个function会不断的轮询所负责的所有socket,当某个socket有数据到达了,就通知用户进程
当用户进程调用了select,那么整个进程会被block
process blocks incall to select, waiting for one possibly many sockets to becom readable.
process blocks while data copied into appliction buffer
##NPM
is a package manager for Node.jsnpm install XXXmoudules
npm init ----> package.json
npm install 会自动install所有需要的包
##Socket
Socket.IO is a JavaScript library for realtime web applications.
##Express RESTful API
var express = require('express');
var app = express();
app.listen(3000);
【Express的framework】
https://segmentfault.com/a/1190000011049112
get 请求
app.get(path,function(request, response)); 第一个参数path为请求的路径 第二个参数为处理请求的回调函数,有两个参数分别是: request 代表请求信息 response 代表响应信息
##为什么不需要Apach这种web-server
nodejs的http库实现了完整HTTP1.1的全部功能(事实上,这部分的源代码正是copy自nginx
##Read html/txt filevar http = require('http');
var url = require('url');
var fs = require('fs');
var q = url.parse(req.url, true);
Parse an address
txt : fs.createReadStream('./txt')
##EventEmitter
var events = require(‘events’);
var eventEmitter = new events.EventEmitter();
/* Assign the event handler to an event(an function) */
Assign the event handler to an event:
eventEmitter.on('scream', myEventHandler);
/* 这里可以传参数*/
eventEmitter.emit('scream');
##Sever.js 和 index.html是如何通讯的
- initial app as a http server
- define a router
use `app.get('/', function(req, res){` use `res.sendFile` function, to router to index.html `res.send` 是send 文字 到页面
- listening on port
- socket on : listening
- socket emit : send
app.use
use()method is used for specifying the 404 handler
Or other public/images
parse request body
app.router
chainable route handlers for a route path
比如get之后又接着post put
app.get
reseponsbile for the requeset : URL/dataapp.post
request dataapp.delete
req.header
Request Headers
res.download() Prompt a file to be downloaded.
res.end() End the response process.
res.json() Send a JSON response.
res.jsonp() Send a JSON response with JSONP support.
res.redirect() Redirect a request.
res.render() Render a view template.
res.send() Send a response of various types.
res.sendFile() Send a file as an octet stream.
res.sendStatus() Set the response status code and send its string representation as the response body.
1.buffer
2.Stream
3.pipe
#Js
Link
JS 继承有哪几种方式
1. Apply() or call() Animal.apply(this,arguments); 2. prototype Dog.prototype = new Animal(); 3. extend
use strict
消除Javascript语法的一些不合理、不严谨之处,减少一些怪异行为; 消除代码运行的一些不安全之处,保证代码运行的安全; 提高编译器效率,增加运行速度; 为未来新版本的Javascript做好铺垫。 2.会将拼写错误转成异常 3.全局变量显式声明 4.禁用with,eval 5.禁止删除声明变量
V8(javascript runtime engine)垃圾回收机制
linkAllocated in memory: garbage collector’s job is to go through objects that are allocated in memory and determine whether they are dead or alive. Those that are alive get to stay in memory, those that are dead get removed, and memory gets allocated back to the heap Dead or alive? The basic check for when an object is dead or alive, is whether or not the client, or the program that executes the code, can reach it
Callstack & heap
V8 allocates memory in the heap as you create
new objects,
V8 divides the heap into two parts:
yung space and old space
you eventually run out memory,
so V8 will have to run a collection to clean up
4.web后端缓存策略有哪些?
1.利用redis(node-redis)或 memcached
在需要缓存的请求到达时,先检查redis数据库是否有
如果不存在,则从对应数据库获取数据,然后将数据写入redis数据库,并设置过期时间。
2.将图片等数据放在CDN缓存,可以大大减轻自己服务器压力
CDN(Content Delivery Network)
5.闭包 Closure
外部函数(external function)获取内部函数私有属性的一种方法
function myHouse(){
var __myname = 'Kevin';
var getMyname = function(){
return __myname;
};
return getMyname;
}
var getName = myHouse();
console.log(getName());//Kevin
即通过在myHouse()中返回getMyname函数,
getMyname函数中返回私有变量__myname,
从而获取私有变量,同时保护私有变量不会直接暴露给外部,
以免改变私有变量值。
ES8新特性
1.String padding
`padStart 和 padEnd` `'es8'.padStart(14, 'wow'); // 'wowwowwowwoes8'`
2.Object.values and Object.entries
Object.values : enumerate all Object.entries : 返回一个给定对象自身可遍历属性 [key, value] 的数组
- Why Express: Its lightweight
1. Support for Connect middleware, allowing many extensions and useful features 2. Use redis to achieve sessions 3. easy templating (based on ejs frame) 4. graceful error handling
- 请说下express 4中app和router的区别 ?
答:express.Router 可以认为是一个微型的只用来处理中间件与控制器的 app,它拥有和 app 类似的方法,例如 get、post、all、use 等等。router它解决了直接把 app 暴露给其它模块使得 app 有被滥用的风险
###1. Why is Node.js Single-threaded?
Node.js is single-threaded for async processing. By doing async processing on a single-thread under typical web loads, more performance and scalability can be achieved as opposed to the typical thread-based implementation.
https://blog.csdn.net/fangjian1204/article/details/50585073
###2. Explain callback in Node.js.
A callback function is called at the completion of a given task. This allows other code to be run in the meantime and prevents any blocking. Being an asynchronous platform, Node.js heavily relies on callback. All APIs of Node are written to support callbacks.
callback hell : result of heavily nested callbacks that make the code not only unreadable but also difficult to maintain
prevent:
- Handle every single error
- Keep your code shallow
- Modularize – split the callbacks into smaller, independent functions that can be called with some parameters then joining them to achieve desired results
###3. Node.js and Ajax
Ajax is primarily designed for dynamically updating a particular section of a page’s content, without having to update the entire page.
Node.js is used for developing client-server applications.
###4. What are “streams” in Node.js? Explain the different types of streams present in Node.js.
Streams are objects that allow reading of data from the source and writing of data to the destination as a continuous process.
There are four types of streams.
to facilitate the reading operation
to facilitate the writing operation
to facilitate both read and write operations
is a form of Duplex stream that performs computations based on the available input